package com.wisdytech.linkdcs.equipment.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.wisdytech.common.handler.ResourceMatchingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.session.UserSession;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DataTransformUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.EquipProperty;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.model.EquipmentMQ;
import com.wisdytech.linkdcs.equipment.service.IEquipmentModelService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentMqService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentParamService;
import com.wisdytech.linkdcs.equipment.service.IEquipmentRegisteredService;
import com.wisdytech.linkdcs.equipment.vo.EquipPropertyVO;
import com.wisdytech.linkdcs.equipment.vo.EquipTaskVO;
import com.wisdytech.linkdcs.equipment.vo.EquipmentRegisterVO;
import com.wisdytech.linkdcs.equipment.vo.MqParamVO;
import com.wisdytech.linkdcs.system.model.SysUser;

/**
 * 
 * <p>
 * ClassName: EquipRegisteredAction
 * </p>
 * <p>
 * Description: 设备注册页面的action层
 * </p>
 * <p>
 * Author: kongming
 * </p>
 * <p>
 * Date: 2017-9-29
 * </p>
 */
@Controller
@RequestMapping("/equipment/register")
public class EquipRegisteredAction {
    /**
     * 注入设备注册equipmentRegisteredService
     */
    @Autowired
    @Qualifier("equipmentRegisterService")
    private IEquipmentRegisteredService equipmentRegisteredService;
    /**
     * 注入设备类别equipmentModelService
     */
    @Autowired
    @Qualifier("equipmentModelService")
    private IEquipmentModelService equipmentModelService;
    
    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;
    @Resource
    private IEquipmentMqService eqMqService;
    
    @Resource
    private IEquipmentParamService equipmentParamService;

    
    @Value("${img.localtion}")
    private String localtion;
    
    /**
    *
    * <p>Description: 设备信息</p>
    * @param model model
    * @return String
    */
   @RequestMapping("/index")
   public String equipmentIndex(Model model, HttpServletRequest httpRequest){
       this.resourceMatchingService.getResourceName(httpRequest,model);
       return "equipment/equipRegistered/registered";
   }

   /**
   *
   * @param equipCode 设备编码
   * @param equipName 设备名称
   * @param operationId 工序Id
   * @param supplier 供应商
   * @param filter 分页参数
   * @return StandardTableResult
   */
  @RequestMapping(value = "/listEquipInfoByFilter/get.mvc")
  @ResponseBody
  public StandardTableResult<Map<String, Object>> listEquipInfoByFilter(String equipCode, String equipName,String operationId,String supplier, Filter filter) {
      PageInfo<Map<String, Object>> page = this.equipmentRegisteredService.listEquipInfoByFilter(equipCode,equipName,operationId,supplier,filter);
      return new StandardTableResult<>(page.getTotal(),page.getList());
  }
    
    
    /**
     * 删除设备信息
     * @param pkId 设备标识id
     * @return 结果对象
     */
    @RequestMapping(value = "/delEquipmentById/del.mvc")
    @ResponseBody
    public StandardResult delEquipmentById(String pkId) {
    	SysUser userSession = BaseUtil.getCurrentUser();
        String loginName = userSession.getUsername();
        return equipmentRegisteredService.delEquipmentById(pkId,loginName);
    }
    
    /**
     * <p>Description: 保存设备对象</p> 
     * @param model 设备对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/saveEquipmentRegister/save.mvc")
    @ResponseBody
    public StandardResult saveEquipmentRegister(@RequestBody Equipment equipment) {
       SysUser userSession = BaseUtil.getCurrentUser();
       String loginName = userSession.getUsername();
        if (StringUtils.isBlank(equipment.getPkId())) {
            return equipmentRegisteredService.addEquipment(equipment, loginName);
        }else {
            return equipmentRegisteredService.updateEquipment(equipment, loginName);
        }
    }
    
    /**
     * <p>Description: 保存设备对象</p> 
     * @param model 设备对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/savePhoto/save.mvc")
    @ResponseBody
    public JSONObject savePhoto(@RequestParam(value = "file", required = false) MultipartFile file,
    		 HttpSession session,HttpServletRequest request) {

       if(!file.isEmpty()){
    	   //保留图片
//           String path = request.getSession().getServletContext().getRealPath("/");  
//           String pathReal = path.substring(0, path.lastIndexOf("webapp"))+"upload";
    	   String pathReal = localtion+"upload";
//           //文件位置存放在tomcat webapp根目录
           String fileName = file.getOriginalFilename();
           String [] fileNames =fileName.split("\\.");
           String realName =DateUtil.getCurDateDefaultStr()+"/"+BaseUtil.getUUID()+"."+fileNames[1];
           
           File targetFile = new File(pathReal, realName);  

           if(!targetFile.getParentFile().exists()){
        	   targetFile.getParentFile().mkdirs();
           }
           //保存  
           JSONObject filePath = new JSONObject();
           filePath.put("path", "upload/"+realName);
           try {  
               file.transferTo(targetFile);  
               return filePath;
           } catch (Exception e) {  
               e.printStackTrace(); 
               //保存失败
               return new JSONObject();
           }
       }
       
       return new JSONObject();
    }
    /**
     * 通过主键id查询对应的设备信息
     * @param pkId 主键id
     * @return 设备信息对象
     */
    @RequestMapping(value = "/getEquipmentRegisterById/get.mvc")
    @ResponseBody
    public StandardResult getEquipmentRegisterById(String pkId) {
        Equipment equipment = equipmentRegisteredService.getEquipmentRegisterById(pkId);
        return  StandardResult.getSuccessResult(equipment);
    }

    /**
     * 刪除圖片
     * @param pkId 主键id
     * @return 设备信息对象
     */
    @RequestMapping(value = "/delImage/del.mvc")
    @ResponseBody
    public StandardResult delImage(String key) {
        return  StandardResult.getSuccessResult();
    }
    
    /**
     * <p>Description:查询设备编号信息列表</p> 
     * @param modelId 设备id
     * @return 设备编号信息列表集合
     */
    @RequestMapping(value = "/listAllEquipmentByOperationId/get.mvc")
    @ResponseBody
    public List<Equipment> listAllEquipmentByOperationId(
    		@ModelAttribute("operationId") String operationId,@ModelAttribute("search") String serach){
    	return equipmentRegisteredService.listAllEquipmentByOperationId(operationId, serach);
    }
    
    /**
     * 通过设备编号查询对应的设备信息
     * @param equipCode 设备编号
     * @return 设备信息对象
     */
    @RequestMapping(value = "/getEquipmentByEquipCode/get.mvc")
    @ResponseBody
    public EquipmentRegisterVO getEquipmentByEquipCode(String equipCode){
        Equipment equipment = equipmentRegisteredService.getEquipmentByEquipCode(equipCode);
        EquipmentRegisterVO registerVO = new EquipmentRegisterVO();
        if (equipment != null) {
            registerVO = DataTransformUtil.changeRegisterVO(equipment);
        }
        return registerVO;
    }
    
    /**
     * 通过设备编号查询对应的设备信息
     * @param equipId 设备id
     * @return 设备信息对象
     */
    @RequestMapping(value = "/getEquipmentByEquipId/get.mvc")
    @ResponseBody
    public EquipmentRegisterVO getEquipmentByEquipId(String equipCode){
        Equipment equipment = equipmentRegisteredService.getEquipmentByEquipCode(equipCode);
        EquipmentRegisterVO registerVO = new EquipmentRegisterVO();
        if (equipment != null) {
            registerVO = DataTransformUtil.changeRegisterVO(equipment);
        }
        return registerVO;
    }
    
    
    /**
     * 
     * <p>Description: 根据设备编号模糊匹配获取数据</p>
     * @param equipCode
     * @return
     */
    @RequestMapping("/searchEquipmentByEquipCode/get.mvc")
    @ResponseBody
    public StandardResult searchEquipmentByCode(Filter filter ,@ModelAttribute("equipCode")String equipCode){
        PageInfo<Equipment>  pageInfo =
                equipmentRegisteredService.searchEquipmentByCode(filter, equipCode);
        //判断是否是最后一页
        if(filter.getNum()>=pageInfo.getPages()){
            return StandardResult.getFailResult("",pageInfo.getList());
        }else{
            return StandardResult.getSuccessResult(pageInfo.getList());
        }
        
    }
    /**
     *
     * <p>Description: 根据设备编号模糊匹配获取数据</p>
     * @param equipCode
     * @return
     */
    @RequestMapping("/searchEquipmentEnvByCode/get.mvc")
    @ResponseBody
    public StandardResult searchEquipmentEnvByCode(Filter filter ,@ModelAttribute("equipCode")String equipCode){
        PageInfo<Equipment>  pageInfo =
                equipmentRegisteredService.searchEquipmentEnvByCode(filter, equipCode);
        //判断是否是最后一页
        if(filter.getNum()>=pageInfo.getPages()){
            return StandardResult.getFailResult("",pageInfo.getList());
        }else{
            return StandardResult.getSuccessResult(pageInfo.getList());
        }

    }
    
    
    
    /**
     * 
     * <p>Description: 根据设备类别id查找</p>
     * @param modelId
     * @return
     */
    @RequestMapping("/listAllEquipment/get.mvc")
    @ResponseBody
    public StandardResult listAllEquipments(String modelId){
        
        List<Equipment>  lists =
                equipmentRegisteredService.listAllEquipment(modelId);
        return StandardResult.getSuccessResult(lists);
    }
    
    
    
    /**
     * 根据设备类别查找mq列表
     * @param modelId
     * @return
     */
    @RequestMapping("/listAllModelMq/get.mvc")
    @ResponseBody
    public StandardResult ListAllModelMq(String modelId){
    	
    	List<Map<String,Object>> data =new ArrayList<>();
    	
    	List<EquipmentMQ>  eqMqLists =
    			eqMqService.getModelMqList(modelId);
    	
    	//获取设备参数列表
    	
    	List<CollectionParam>  collectionParams=
    			equipmentParamService.listModelParams(modelId);

    	//组合成需要数据对象
    	
    	//尚未分配
    	if(eqMqLists.isEmpty()){
    		
    		//单个节点
    		Map<String,Object> oneList=new HashMap<>();
    		List<MqParamVO> paramList=new ArrayList<MqParamVO>();	
    		for(CollectionParam param : collectionParams){
    			MqParamVO vo =new MqParamVO();
    			vo.setPkId(param.getPkId());
    			vo.setName(param.getParamName());
    			vo.setIsSelected(false);
    			paramList.add(vo);
    		}
    		oneList.put("name", "");
    		oneList.put("data", paramList);

    		data.add(oneList);
    		return StandardResult.getSuccessResult(data);
    		
    	}
    	
    	Map<String,Set<String>> mqLists=new HashMap<>();
    	//已分配
    	for(EquipmentMQ eMq:eqMqLists){
    		
    		Set<String> mqParamList;
    		//循环出队列信息
    		if(mqLists.containsKey(eMq.getMqName())){
    			mqParamList=mqLists.get(eMq.getMqName());
    		}else{
    			mqParamList=new HashSet<String>();
    			mqLists.put(eMq.getMqName(), mqParamList);
    		}
    		mqParamList.add(eMq.getParamId());
    	}
    	
    	//循环补充全部的参数
    	Set<String> mqListKeys=mqLists.keySet();
    	for(String mqListKey : mqListKeys){
    		//已经勾选的参数
    		Set<String>  paramIds =mqLists.get(mqListKey);
    		
    		//单个节点
    		Map<String,Object> oneList=new HashMap<>();
    		List<MqParamVO> paramList=new ArrayList<MqParamVO>();	
    		for(CollectionParam param : collectionParams){
    			MqParamVO vo =new MqParamVO();
    			vo.setPkId(param.getPkId());
    			vo.setName(param.getParamName());
    			vo.setIsSelected(paramIds.contains(param.getPkId()));
    			paramList.add(vo);
    		}
    		oneList.put("name", mqListKey);
    		oneList.put("data", paramList);

    		data.add(oneList);
    	}
    	
    	
    	return StandardResult.getSuccessResult(data);
    }
    
    
    @RequestMapping("/saveModelMq/save.mvc")
    @ResponseBody
    public StandardResult saveModelMq(@ModelAttribute("data")String data){
    	
    	//解析保存mq队列
    	JSONObject object=JSON.parseObject(data);
    	
    	//设备类别ID
    	String modelId =object.getString("modelId");
    	
    	//参数对应的信息
    	List<EquipmentMQ> params=new ArrayList<>();
    	
    	List<String> mqDatas=JSON.parseArray(object.getString("data"),String.class);
    	//进行队列保存
    	for(String mqData:mqDatas){
    		//多个队列
    		String [] mqDataStrs =mqData.split(";");
    		//队列名称
    		String mqName =mqDataStrs[0];
    		//队列参数列表
    		String mqStrs =mqDataStrs[1];
    		mqStrs.substring(0, mqStrs.length()-1);
    		String [] paramIdsArray=mqStrs.split(",");
    		
    		for(String paramId : paramIdsArray){
    			EquipmentMQ eMq =new EquipmentMQ();
    			eMq.setModelId(modelId);
    			eMq.setMqName(mqName);
    			eMq.setParamId(paramId);
    			eMq.setPkId(UUID.randomUUID().toString());
    			params.add(eMq);
    		}
    	}
    	
    	//调用接口保存
    	
    	eqMqService.insert(modelId, params);

    	return StandardResult.getSuccessResult();
    }
    
    /**
     * 分页查询 设备参数
     * @param search 参数名称匹配
     * @param page 页面数
     * @param size 每页大小
     * @return 设备类别对应的参数列表
     */
    @RequestMapping("/listModelParams/get.mvc")
    @ResponseBody
    public StandardResult listModelParams(@ModelAttribute("modelId")String modelId){
    	
    	List<Map<String,Object>> data =new ArrayList<>();
    	List<CollectionParam>  collectionParams =
    			equipmentParamService.listModelParams(modelId, "", 1, Integer.MAX_VALUE);
    	
    	//单个节点
		Map<String,Object> oneList=new HashMap<>();
		List<MqParamVO> paramList=new ArrayList<MqParamVO>();	
		for(CollectionParam param : collectionParams){
			MqParamVO vo =new MqParamVO();
			vo.setPkId(param.getPkId());
			vo.setName(param.getParamName());
			vo.setIsSelected(false);
			paramList.add(vo);
		}
		oneList.put("name", "");
		oneList.put("data", paramList);

		data.add(oneList);
		return StandardResult.getSuccessResult(data);
		
		
    }
    
    /**
     * 
     * <p>Description: 根据设备类别id查找</p>
     * @param modelId
     * @return
     */
    @RequestMapping("/equipCodeChangeByeqCode/get.mvc")
    @ResponseBody
    public StandardResult equipCodeChangeByeqCode(String equipCode){
        Equipment  equipment =equipmentRegisteredService.equipCodeChangeByeqCode(equipCode);
        EquipTaskVO equipTaskVO = new EquipTaskVO();
        equipTaskVO.setAreaName(equipment.getAreaName());
        equipTaskVO.setEquipName(equipment.getEquipName());
        equipTaskVO.setFatoryName(equipment.getFactoryName());
        equipTaskVO.setLineName(equipment.getLineName());
        equipTaskVO.setShopName(equipment.getShopName());
        equipTaskVO.setResponsiblePerson(equipment.getResponsiblePerson());
        equipTaskVO.setDepartment(equipment.getDepartment());
        return StandardResult.getSuccessResult(equipTaskVO);
    }
    /**
    *
    * @param operationId 工序Id
    * @param filter 分页参数
    */
   @RequestMapping(value = "/getAidEquips/get.mvc")
   @ResponseBody
   public StandardResult getAidEquips(String operationId) {
       List<Equipment> list = this.equipmentRegisteredService.getAidEquips(operationId);
       return StandardResult.getSuccessResult(list);
   }
    
   /**
   * @param aidEquipCode 辅助类设备编码
   */
   @RequestMapping("/delAidEquip/del.mvc")
   @ResponseBody
   public StandardResult delAidEquip(String equipCode,String aidEquipCode) {
   	if(StringUtils.isBlank(aidEquipCode)) {
   		return StandardResult.getFailResult("辅助设备编码为空");
   	}  	
   	equipmentRegisteredService.delAidEquip(equipCode, aidEquipCode);
   	return StandardResult.getSuccessResult();
		
   }
   
   /**
    * 根据设备Code查询设备信息
    * @param equipCode 设备code
    * @return StandardResult
    */
   @RequestMapping(value = "/getEquipInfoByCode/get.mvc")
   @ResponseBody
   public StandardResult getEquipInfoByCode(String equipCode) {
       Equipment equip = equipmentRegisteredService.getEquipInfoByCode(equipCode);
       return StandardResult.getSuccessResult(equip);
   }
   
   
   /**
    * <p>Description: 保存参数对象</p>
    * @param file 上传的文件对象
    * @return 处理结果对象
    */
   @RequestMapping(value = "/batchImportEquip/save.mvc")
   @ResponseBody
   public StandardResult batchImportEquip(@RequestParam(value = "file", required = false) MultipartFile file) {
       if (file==null) {
           return StandardResult.getFailResult("文件上传失败");
       }
       SysUser operator = BaseUtil.getCurrentUser();
       this.equipmentRegisteredService.batchImportEquip(file,operator);
       return StandardResult.getSuccessResult("数据导入成功",null);
   }
   
   
   @RequestMapping(value = "/listPropertyValueAll/get.mvc")
   @ResponseBody
   public StandardTableResult<EquipPropertyVO> listPropertyValueAll(String pkId, Filter filter) {
       PageInfo<EquipPropertyVO> page = this.equipmentRegisteredService.listPropertyValueAll(pkId,filter);
       return new StandardTableResult<EquipPropertyVO>(page.getTotal(),page.getList());
   }
   
   
   @RequestMapping(value = "/listPropertyValueAllByPkId/get.mvc")
   @ResponseBody
   public StandardResult listPropertyValueAllByPkId(String equipCode, Filter filter) {
       PageInfo<EquipPropertyVO> page = this.equipmentRegisteredService.listPropertyValueAllByPkId(equipCode,filter);
       return StandardResult.getSuccessResult(page.getList());
   }
   
   /**
    * 通过主键id查询对应的设备详情
    * @param pkId 主键id
    * @return 设备信息对象
    */
   @RequestMapping(value = "/getEquipmentRegisterDetilById/get.mvc")
   @ResponseBody
   public StandardResult getEquipmentRegisterDetilById(String pkId) {
       Equipment equipment = equipmentRegisteredService.getEquipmentRegisterDetilById(pkId);
       return  StandardResult.getSuccessResult(equipment);
   }
    
   
   /**
   *
   * <p>Description: 下载文件</p>
   */
  @RequestMapping(value = "/downloadImportTemplate/get.mvc")
  //@ResponseBody
  public ResponseEntity<FileSystemResource> download() throws UnsupportedEncodingException {
      //String filename = URLEncoder.encode("工装保养项导入模板.xlsx", StandardCharsets.UTF_8.displayName());
      String filename = new String("设备信息导入模板.xlsx".getBytes("gb2312"),"ISO-8859-1");
      HttpHeaders headers = new HttpHeaders();
      headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
      headers.add("Content-Disposition", "attachment; filename=" + filename);
      headers.add("Pragma", "no-cache");
      headers.add("Expires", "0");
      File file = null;
      try {
          file = ResourceUtils.getFile("classpath:static/excelTemplates/设备信息导入模板.xlsx");
      } catch (FileNotFoundException e) {
          e.printStackTrace();
          return null;
      }
      return ResponseEntity
              .ok()
              .headers(headers)
              .contentLength(file.length())
              .contentType(MediaType.parseMediaType("application/octet-stream"))
              .body(new FileSystemResource(file));
  }


    /**
     * <p>Description: 根据设备类别id查找</p>
     *
     * @param modelId
     * @return
     */
    @RequestMapping("/listAllEquipmentByModelCode/get.mvc")
    @ResponseBody
    public StandardResult listAllEquipmentsByCode(String modelCode) {

        List<Equipment> lists =
                equipmentRegisteredService.listAllEquipmentByModelCode(modelCode);
        return StandardResult.getSuccessResult(lists);
    }
  
    
}
